package openapi

import (
	"strings"

	"gitee.com/bjf-fhe/apinx/errors"
	"github.com/getkin/kin-openapi/openapi3"
)

func AddMethod(def *openapi3.T, path, method string) (*openapi3.Operation, string) {
	if def.Paths == nil {
		def.Paths = &openapi3.Paths{}
	}
	var pDef *openapi3.PathItem
	if pDef = def.Paths.Find(path); pDef == nil {
		pDef = new(openapi3.PathItem)
	}
	method = strings.ToLower(method)
	var op = new(openapi3.Operation)
	switch method {
	case "get":
		pDef.Get = op
	case "post":
		pDef.Post = op
	case "put":
		pDef.Put = op
	case "delete":
		pDef.Delete = op
	case "options":
		pDef.Options = op
	case "head":
		pDef.Head = op
	case "patch":
		pDef.Patch = op
	case "trace":
		pDef.Trace = op
	case "connect":
		pDef.Connect = op
	}
	def.Paths.Set(path, pDef)
	return op, method
}

// GetOperation 按调用参数从配置中选择合适的method
func GetPathAndMethod(def *openapi3.T, pName, mName string) (path *openapi3.PathItem, op *openapi3.Operation, err error) {

	path = def.Paths.Find(pName)
	if path == nil {
		err = errors.New(errors.ERR_NO_SUCH_PATH)
		return
	}

	mName = strings.ToLower(mName)

	switch mName {
	case "get":
		op = path.Get
	case "post":
		op = path.Post
	case "put":
		op = path.Put
	case "delete":
		op = path.Delete
	case "options":
		op = path.Options
	case "head":
		op = path.Head
	case "patch":
		op = path.Patch
	case "trace":
		op = path.Trace
	case "connect":
		op = path.Connect
	}
	if op == nil {
		err = errors.New(errors.ERR_NO_SUCH_METHOD)
	}
	return
}

// GetOperation 按调用参数从配置中选择合适的method
func GetOperation(path *openapi3.PathItem, mName string) (op *openapi3.Operation, err error) {

	mName = strings.ToLower(mName)

	switch mName {
	case "get":
		op = path.Get
	case "post":
		op = path.Post
	case "put":
		op = path.Put
	case "delete":
		op = path.Delete
	case "options":
		op = path.Options
	case "head":
		op = path.Head
	case "patch":
		op = path.Patch
	case "trace":
		op = path.Trace
	case "connect":
		op = path.Connect
	}
	if op == nil {
		err = errors.New(errors.ERROR_UNKNOWN_METHOD)
	}
	return
}
